/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package experimental.com.rhythm.commons.validation.bean;

import experimental.com.rhythm.commons.validation.bean.annotation.NotEmpty;
import java.lang.reflect.Field;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Michael J. Lee
 */
public class NotEmptyConstraintValidator extends ConstraintValidator<NotEmpty> {

    @Override
    public void checkConstraint(Object value) {
        NotEmpty constraint = getInstance();

        checkNotNull(value, constraint);
        checkNotEmptyString(value, constraint);

    }

    private void checkNotNull(Object fieldValue, NotEmpty constraint) throws ConstraintVolationException {
        if (fieldValue == null) {
            throw new ConstraintVolationException(constraint.message());
        }
    }

    private void checkNotEmptyString(Object fieldValue, NotEmpty constraint) throws ConstraintVolationException {
        if (fieldValue instanceof String) {
            final String fieldString = getInstance().message();
            if (fieldString.length() == 0) {
                throw new ConstraintVolationException(constraint.message());
            }
        }
    }

    private Object invokeValue(Field field, Object ref) {
        Object fieldValue = null;
        try {
            fieldValue = field.get(ref);
        } catch (Exception ex) {
            Logger.getLogger(NotEmptyConstraintValidator.class.getName()).log(Level.SEVERE, null, ex);
            throw new RuntimeException(ex);
        }
        return fieldValue;
    }
}
